﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Microsoft.ServiceHosting.ServiceRuntime;
using Microsoft.Samples.ServiceHosting.StorageClient;
using System.Data.Services.Client;
using System.Net;
using System.Globalization;
using System.Collections.Generic;

namespace Inscription_WebRole
{
    public partial class _Default : BlogEngine.Core.Web.Controls.BlogBasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
           
        }

        protected void ValidateBtn_Click(object sender, EventArgs e)
        {

            StorageAccountInfo account = null;

            try
            {
                //Identification
                account = StorageAccountInfo.GetDefaultTableStorageAccountFromConfiguration();
                DataServiceContext svc = new DataServiceContext(account);
                svc.RetryPolicy = RetryPolicies.RetryN(3, TimeSpan.FromSeconds(1));

                ////Table creation
                TableStorage tableStorage = TableStorage.Create(account);
                //tableStorage.TryCreateTable(DataServiceContext.tableName);
               

                //List all tables in the account
                IEnumerable<string> tables2 = tableStorage.ListTables();
                foreach (string n1 in tables2)
                {
                    System.Diagnostics.Debug.WriteLine("nom table : " + n1);
                }

                //string TableName = DataServiceContext.tableName;

                Inscription newInscription = new Inscription("inscriptionPK",emailTB.Text);

                newInscription.firstName = firstnameTB.Text;
                newInscription.lastName = lastnameTB.Text;
                newInscription.email = emailTB.Text;
                newInscription.interest = interestRBL.Text;


                for (int i = 0; i < suscribtionCBL.Items.Count; i++) // 0 = newsletter zeCloud
                {                                                    // 1 = newsletter partner
                    if (suscribtionCBL.Items[i].Selected)             // 2 = TechDays in live 
                    {
                        newInscription.subscription += i.ToString();
                    }
                }

                svc.AddObject(DataServiceContext.tableName, newInscription as Inscription); //Add Inscription to the table 

                try
                {
                    svc.SaveChangesWithRetries();
                    System.Diagnostics.Debug.WriteLine("Validatation");
                    errorLbl.Text = "Email enregistré";
                }
                catch (Exception ex)
                {
                    HttpStatusCode status;
                    StorageExtendedErrorInformation errorInfo;

                    if (TableStorageHelpers.EvaluateException(ex, out status, out errorInfo)
                        && status == HttpStatusCode.Conflict)
                    {
                        // the row has already been inserted before, this is expected here
                        if (errorInfo != null)
                        {
                            System.Diagnostics.Debug.WriteLine(String.Format("Attempting to insert row with same keys resulted in error {0} : {1}",
                                               errorInfo.ErrorCode, errorInfo.ErrorMessage));

                            errorLbl.Text = "Utilisateur déjà enregistré";
                        }
                    }
                    else
                        throw;
                }
            }
            catch (DataServiceRequestException dsre)
            {
                System.Diagnostics.Debug.WriteLine("DataServiceRequestException: " + GetExceptionMessage(dsre));
                ShowTableStorageErrorMessage(account.BaseUri.ToString());
            }
            catch (InvalidOperationException ioe)
            {
                System.Diagnostics.Debug.WriteLine("Storage service error: " + GetExceptionMessage(ioe));
                ShowTableStorageErrorMessage(account.BaseUri.ToString());
            }
        }

        private static void ShowTableStorageErrorMessage(string endpoint)
        {
            Console.WriteLine("Please check if the table storage service is running at " + endpoint);
            Console.WriteLine("Detailed information on how to run the development table storage tool " +
                              "locally can be found in the readme file that comes with this sample.");
            Console.WriteLine("Also make sure that you started the table service with the right parameters, " +
                              "that is, exactly as described in the readme file for this sample.");
        }

        private static string GetExceptionMessage(Exception exception)
        {
            HttpStatusCode statusCode;
            StorageExtendedErrorInformation extendedErrorInfo;
            if (TableStorageHelpers.EvaluateException(exception, out statusCode, out extendedErrorInfo))
            {
                if (extendedErrorInfo != null)
                {
                    return string.Format(CultureInfo.InvariantCulture, "{0} {1}", extendedErrorInfo.ErrorCode ?? "", extendedErrorInfo.ErrorMessage ?? "");
                }
            }

            DataServiceClientException dse = exception.InnerException as DataServiceClientException;
            if (dse != null)
                return dse.Message;
            else
                return exception.Message;
        }
    }
}
